package com.cn.yunhe.rentcars.security;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.cn.yunhe.rentcars.mapper.permission.ResourceMapper;
import com.cn.yunhe.rentcars.model.permission.Resource;

/**
 * 
 * SHIRO 配置
 * 
 * @author 刘源
 */
@Configuration
public class ShiroConfiguration {

    private static Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class);
    
    @Bean(name="ShiroRealmImpl")
    public ShiroRealmImpl getShiroRealm(){
        return new ShiroRealmImpl();
    }

    @Bean(name="shrioEhcacheManager")
    public EhCacheManager getEhCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        ehCacheManager.setCacheManagerConfigFile("classpath:config/ehcache-shiro.xml");
        return ehCacheManager;
    }

    @Bean(name="lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(getShiroRealm());
        defaultWebSecurityManager.setCacheManager(getEhCacheManager());
        return defaultWebSecurityManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(getDefaultWebSecurityManager());
        return authorizationAttributeSourceAdvisor;
    }
    
    
    /**
     * 加载shiroFilter权限控制规则（从数据库读取然后配置）
     *
     * @author ZSL
     * @create 2016年7月24日
     */
    private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean, ResourceMapper resourceMapper){

    	Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //List<Syspermission> permissionList = permissionMapper.getPermissions();
        /*for(Syspermission permission:permissionList){
        	filterChainDefinitionMap.put(permission.getUrl(), "authc,perms["+permission.getPermission()+"]");
        	logger.info("##################系统权限【"+permission.getPermission()+"】##################");
        }*/
    	
    	List<Resource> resourceList = resourceMapper.searchResources();
        for(Resource resource:resourceList){
        	filterChainDefinitionMap.put(resource.getRelateURL(), "authc,perms["+resource.getPermisCode()+"]");
        	logger.info("##################系统权限【"+resource.getPermisCode()+"】##################");
        }
        filterChainDefinitionMap.put("/home", "authc");
        filterChainDefinitionMap.put("/**", "anon");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    }

    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager, ResourceMapper resourceMapper){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/");
        // 登录成功后要跳转的连接
        shiroFilterFactoryBean.setSuccessUrl("/home");
        // 权限校验失败后要跳转的连接
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        loadShiroFilterChain(shiroFilterFactoryBean,resourceMapper);
        return shiroFilterFactoryBean;
    }


}
